package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.util.List;

public class TeacherTaughtCoursesController implements TeacherSubController {

    @FXML
    private TableView<TaughtCourse> taughtCoursesTableView;
    @FXML
    private TableColumn<TaughtCourse, String> courseNameColumn;
    @FXML
    private TableColumn<TaughtCourse, String> semesterColumn;

    private TeacherController teacherController;
    private User currentUser;
    private TaughtCourseDAO taughtCourseDAO;

    @Override
    public void setPrimaryStage(javafx.stage.Stage primaryStage) {
        // 不需要在这里设置primaryStage，由主控制器处理
    }

    @Override
    public void setTeacherController(TeacherController teacherController) {
        this.teacherController = teacherController;
    }

    public void setCurrentUser(User user) {
        this.currentUser = user;
        System.out.println("TeacherTaughtCoursesController: setCurrentUser called with user: " + (user != null ? user.getUsername() : "null"));
        // 在设置完 currentUser 后尝试加载数据
        attemptLoadTaughtCourseData();
    }

    @FXML
    public void initialize() {
        // 初始化 DAO
        taughtCourseDAO = new TaughtCourseDAO();

        // 设置表格列与 TaughtCourse 对象的属性关联
        courseNameColumn.setCellValueFactory(new PropertyValueFactory<>("courseName"));
        semesterColumn.setCellValueFactory(new PropertyValueFactory<>("semester"));

        // 表格数据将在 setCurrentUser 后加载，这里不直接加载
        System.out.println("TeacherTaughtCoursesController initialized.");
        // 尝试在初始化后加载数据，以防 setCurrentUser 在 initialize 之前被调用（尽管不常见）
        attemptLoadTaughtCourseData();
    }

    private void attemptLoadTaughtCourseData() {
        System.out.println("attemptLoadTaughtCourseData called.");
        if (currentUser != null && taughtCourseDAO != null) {
            System.out.println("Attempting to load taught courses for teacher: " + currentUser.getUsername());
            List<TaughtCourse> courses = taughtCourseDAO.getTaughtCoursesByTeacherUsername(currentUser.getUsername());
            System.out.println("Fetched " + courses.size() + " courses from DB.");
            ObservableList<TaughtCourse> observableCourses = FXCollections.observableArrayList(courses);
            taughtCoursesTableView.setItems(observableCourses);
            System.out.println("Loaded " + courses.size() + " taught courses for teacher " + currentUser.getUsername());
        } else {
            System.out.println("currentUser or taughtCourseDAO is null. Cannot load taught course data yet.");
        }
    }

    // TODO: 添加其他处理方法，例如查看课程详情等
}